4. What is the result of the following code?
A. OneCode:x=0; switch(x) { case 1: printf( "One" ); case 0: printf( "Zero" ); case 2: printf( "Hello World" ); }
B. Zero
C. Hello World
D. ZeroHello World
why it is D, I thought it should be B
4. What is the result of the following code?
A. OneCode:x=0; switch(x) { case 1: printf( "One" ); case 0: printf( "Zero" ); case 2: printf( "Hello World" ); }
B. Zero
C. Hello World
D. ZeroHello World
why it is D, I thought it should be B
Because cases fall-through to the next case unless you use the break statement.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
if "break;" statement is used then UR expected option B will be the result
Rahmet
rahmetOriginally Posted by Salem
so you mean after printing Zero the program doesn`t check if
case (2 == x) and it will print anything after case 0
No it doesn't.
The switch condition is only checked once, and that decides where in the switch statement the program jumps to. After that, the code just executes in a linear fashion like any other code until it comes to the closing brace or a break statement.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.